package com.study.util;

import cn.hutool.db.DbRuntimeException;
import cn.hutool.db.ds.simple.AbstractDataSource;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 封装JDBC 的工具类
 */
public class MySqlDataSource extends AbstractDataSource {

    /**
     * 数据库驱动
     */
    private static final String DRIVER = "com.mysql.jdbc.Driver";

    /**
     * jdbc url
     */
    private static final String URL = "jdbc:mysql://121.42.157.181:3306/test";

    /**
     * 用户名
     */
    private static final String USER = "root";

    /**
     * 密码
     */
    private static final String PASSWORD = "tongxing2018";


    /**
     * 初始化MySql的驱动
     *
     */
    public void init() {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            throw new DbRuntimeException(e, "Get jdbc driver [{}] error!", DRIVER);
        }
    }


    public MySqlDataSource() {
        init();
    }

    @Override
    public void close() throws IOException {
    }

    @Override
    public Connection getConnection(){
        try{
            return DriverManager.getConnection(URL, USER, PASSWORD);
        }catch (SQLException sqlException){
            return null;
        }
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return getConnection();
    }
}
